<?php
namespace common\service;

use Yii;
use yii\helpers\Url;
use yii\helpers\Json;
use yii\web\HttpException;
use common\models\YwUser;
use common\models\YwUserWeixin;
use common\models\YwTicket;
use common\models\YwSite;
use common\classes\YcWeixin;
use common\service\YsIp;
use common\components\Request;
use GuzzleHttp\json_decode;

class YsWeixin extends Service{
    public $refreshTokenCode = [40001, 42001, 40014, 40030];
    public $warningCode = [50002, 48001, 48004];
    private $_siteInfo=false,$_siteParams=false;
    private $_redis = false;

    public function getSiteInfo(){
        if($this->_siteInfo === false){
            $this->_siteInfo = Yii::$app->site->siteInfo;
        }
        return $this->_siteInfo;
    }
    public function getSiteParams(){
        if($this->_siteParams === false){
            $this->_siteParams = json_decode($this->siteInfo['params'],true);
        }
        return $this->_siteParams;
    }

    /**
     * 加载数据
     * @param $siteId
     * @param bool|false $data
     * @return mixed
     */
    public function loadSiteInfo($siteId,$data=false){
        if($data){
            $this->_siteInfo = $data;
        }else{
            $this->_siteInfo = YwSite::find()->where(['id'=>intval($siteId)])->asArray()->one();
        }
        return $this;
    }

    public function getRedis(){
        if($this->_redis === false){
            $this->_redis = Yii::$app->redis;
        }
        return $this->_redis;
    }

    public static function isWeixinBrowser(){
        $userAgent = strtolower(Yii::$app->getRequest()->getUserAgent());
        if(strpos($userAgent, 'micromessenger') === false){
            return false;
        }
        if(strpos(strtolower($userAgent), 'windows') || strpos(strtolower($userAgent), 'firefox')){
            return false;
        }
        return true;
    }

    public static function isApp(){
        $userAgent = Yii::$app->getRequest()->getUserAgent();
        if(strpos($userAgent, 'YourBigFather') !== false){
            return true;
        }
        return false;
    }

    public function get_by_curl($url,$post = false){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT,10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        if($post){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
        }
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * 获取微信的access_token
     * @param bool|false $reset
     * @return bool
     */
    public function getAccessToken($reset = false){
        if($reset){
            return YcWeixin::classes()->refresh()->accessToken($this->siteInfo['id']);
        }else{
            return YcWeixin::classes()->accessToken($this->siteInfo['id']);
        }
    }

    /**
     * 获取微信jsapi_ticket
     * @param bool|false $reset
     * @return bool|mixed
     */
    public function getJsapiTicket($reset = false){
        if($reset){
            return YcWeixin::classes()->refresh()->jsapiTicket($this->siteInfo['id']);
        }else{
            return YcWeixin::classes()->jsapiTicket($this->siteInfo['id']);
        }
    }

    /**
     * 发送自定义的模板消息
     * @param $touser
     * @param $template_id
     * @param $url
     * @param $data
     * @param string $topcolor
     * @return bool
     */
    public function templateMessage($userId, $templateId, $detailUrl, $data, $topColor = '#7B68EE')
    {
    	$userMOdel = YwUser::findOne($userId);
    	$template = array(
    		'touser' => $userMOdel->weixin_openid,
    		'template_id' => $templateId,
    		'url' => $detailUrl,
    		'topcolor' => $topColor,
    		'data' => $data
    	);
    	$accessJson = YcWeixin::classes()->getAccessToken($userMOdel->site_id);
    	$tokenArray = Json::decode($accessJson,true);
    	//$sendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $this->getAccessToken();
    	$sendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $tokenArray['access_token'];
    	$template = json_encode($template);
    	$resultJson = $this->get_by_curl($sendUrl, $template);
    	$resultArray = Json::decode($resultJson, true);
    	if ($resultArray['errcode'] == 0) {
    		return true;
    	} else {
    		Yii::error('YsWeixin/templateMessage args:'.print_r(func_get_args(),true).' sendurl:'.$sendUrl.' return:'.print_r($resultArray,true));
    		return false;
    	}
    }
    
    /**
     * 发送自定义的客服消息
     * @param $touser
     * @param $data
     * @return bool
     */
    public function staffMessage($siteId, $openid, $articles)
    {
        //print_r($data);
        //$data = (new Request())->encode_json((array)$data);
        $articleArr = json_decode($articles);
        if(empty($articleArr)){
            return false;
        }
        $myArticles = array();
        foreach ($articleArr as $article){
            $myArticle = (array)$article;
            array_push($myArticles, $myArticle);
        }
        $message = array(
             'touser' => $openid,
             'msgtype' => 'news',
             'news' => array(
                  'articles' => $myArticles
             )
        );
        $message = (new Request())->encode_json($message);
        $accessJson = YcWeixin::classes()->getAccessToken($siteId);
        $tokenArray = Json::decode($accessJson,true);
        //$sendUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $this->getAccessToken();
        $sendUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $tokenArray['access_token'];
        $resultJson = $this->get_by_curl($sendUrl, $message);
        $resultArray = Json::decode($resultJson, true);
        if ($resultArray['errcode'] == 0) {
            return true;
        } else {
            Yii::error('YsWeixin/staffMessage args:'.print_r(func_get_args(),true).' sendurl:'.$sendUrl.' return:'.print_r($resultArray,true));
            return false;
        }
    }
    
    
    //获取微信二维码
    public function getQrcodeTicket($userId,$newaccess = false){
        if(empty($userId)){
            return false;
        }
        //处理二维码
        if (Yii::$app->user->isGuest || $newaccess){
            $siteInfor = \common\classes\YcSite::classes()->siteInfoList();
            $startNum = 0;
            $siteId = 0;
            $lastTwoUserId = substr($userId,-2);
            foreach ($siteInfor as $key=>$site){
                if($site->blockade != 10){
                    continue;
                }
                $endNum = $startNum + $site->percent;
                if ($lastTwoUserId >= $startNum && $lastTwoUserId < $endNum){
                    $siteId = $site->id;
                    break;
                }
                $startNum += $site->percent;
            }

            if ($siteId == 0){
                $num = count($siteInfor);
                $day = date('d',time());
                $siteKey = ($day+$userId) % $num;
                $siteId = $siteInfor[$siteKey]->id;
            }
        }else {
            $siteId = Yii::$app->user->identity->site_id;
            if ($siteId == 0){
                $siteId = 27;
            }
            $siteInfor_ = YwSite::findOne(['id'=>$siteId]);
            if ($siteId > 10 || $siteInfor_->status == 0 || $siteInfor_->blockade != 10){
                $siteInfor_1 = YwSite::find()->where('id<=10 AND status>0 AND blockade=10')->one();
                if (!empty($siteInfor_1) && isset($siteInfor_1->id)){
                    $siteId = $siteInfor_1->id;
                }else{
                    return $this->getQrcodeTicket($userId,true);
                }
            }
        }
        $cacheKey = 'zhuanfa:'.$siteId.$userId;
//         if ($userId == 30012){
//             Yii::$app->redis->DEL($cacheKey);
//         }
        try {
            $ticket = Yii::$app->redis->GET($cacheKey);
        } catch (Exception $ex) {
            Yii::warning("Ysweixin/QrcodeTicket redis cache error:" . $ex->getMessage() , __METHOD__ );
            $ticket = false;
        }
        if(!empty($ticket)){
            return $ticket;
        }
        Yii::error('Ysweixin/getQrcode cache miss');

        $accessToken = $this->loadSiteInfo($siteId)->getAccessToken();
        $post = '{
            "expire_seconds": 604800,
            "action_name": "QR_SCENE",
            "action_info": {
                "scene": {
                    "scene_id": '.$userId.'
                }
            }
        }';
       
        $qrcodeTicketUrl = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$accessToken;
    
        
        $dataJson = $this->get_by_curl($qrcodeTicketUrl,$post);
        $data = json_decode($dataJson,true);
        if(isset($data['ticket']) == false || empty($data['ticket'])){
            if(isset($data['errcode']) && in_array($data['errcode'], $this->refreshTokenCode)){
                $accessToken = $this->getAccessToken(true);
            }
            Yii::error('Ysweixin/getQrcodeTicket qrcodeTicketUrl:'.$qrcodeTicketUrl.'  error:'.print_r($data,true));
            return false;
        }
        $ticket = urlencode($data['ticket']);
        Yii::$app->redis->setex($cacheKey,432000,$ticket);//二维码缓存12小时
        return $ticket;
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 微信分享
     * @return array
     */
    public function getSignPackage() {
        $jsapiTicket = $this->getJsapiTicket();

        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->siteParams['appId'],
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    /**
     * 微信登录的两种方式
     * @param type $code
     * @param type $state
     * @param type $type menu page
     */
    public function login($code,$state = 0,$type = 'menu'){
        if(empty($code)){
            return $this->returnArray([],100,'CODE不能为空');
        }
        $url = Yii::$app->getHomeUrl();
        if ($state == 2) {
            $url = Url::to(['help/new']);
        }elseif ($state == 3){
            $url = Url::to(['user/cash']);
        }
        
        //用户微信信息
        $weixinData = [
            'appid'=>$this->siteParams['appId'],
            'site_id'=>$this->siteInfo['id'],
            'type' => 1,
        ];
        
        //获得openid
        $openidUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->siteParams['appId'].'&secret='.$this->siteParams['secret'].'&code='.$code.'&grant_type=authorization_code';
        $data = $this->get_by_curl($openidUrl);
        $data = json_decode($data,true);
        if(isset($data['errcode']) || empty($data['openid'])){
            Yii::error('YsWeixin/login GET openid openidUrl:'.$openidUrl.' args:'.print_r(func_get_args(),true).' error:'.print_r($data,true));
            return $this->returnArray([],10,'登录微信失败');
        }
        foreach($data as $key=>$val){
            $weixinData[$key] = $val;
        }

        /*
        if (!Yii::$app->user->isGuest && Yii::$app->user->identity->weixin_unionid == $weixinData['unionid']){
            return $this->returnArray(['url'=>$url],0,'登录微信成功');
        }
         */
        //若存在微信资料，则写入数据(即数据库和COOKIE)，登录成功。
        $weixinInfo = YwUserWeixin::findOne(['openid'=>$weixinData['openid'],'site_id'=>$weixinData['site_id']]);
        if(!empty($weixinInfo)){
            //记录用户上次访问的时间
            $weixinInfo->updated_at = time();
            if($weixinInfo->save(false,['updated_at']) === false){
                Yii::error('YsWeixin/login update error:'.print_r($weixinInfo->errors,true));
            }
            //为用户记录上次访问的公众号
            $currentUser = YwUser::findOne(['id'=>$weixinInfo->user_id]);
            $currentUser->weixin_openid = isset($weixinData['openid']) ? $weixinData['openid'] : '';
            $currentUser->site_id = isset($weixinData['site_id']) ? $weixinData['site_id'] : '';
            if($currentUser->save(false,['site_id','weixin_openid']) === false){
                Yii::error('YsWeixin/login update user error:'.print_r($currentUser->errors,true));
            }
            //如果COOKIE存在，则表示登录成功
            if (!Yii::$app->user->isGuest && Yii::$app->user->id == $weixinInfo->user_id){
                return $this->returnArray(['url'=>$url],0,'登录微信成功');
            }
            if (!empty($weixinInfo->userInfo) && Yii::$app->getUser()->login($weixinInfo->userInfo,3600 * 720)){
                Yii::$app->getSession()->setFlash('loginuid', $weixinInfo->userInfo->id);
                return $this->returnArray(['url'=>$url],0,'登录微信成功');
            }
        }

        //若不存在微信资料，以下全部代码通过两种接口方式获得获得数据，写入数据库，模拟COOKIE登录。
        if($type == 'menu'){
            $access_token = $this->getAccessToken();
            $wxUserInfoUrl = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$weixinData['openid'].'&lang=zh_CN';
        }else{
            $access_token = $weixinData['access_token'];
            $wxUserInfoUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token .'&openid='.$weixinData['openid'].'&lang=zh_CN';
        }
        $wxUserinfo = $this->get_by_curl($wxUserInfoUrl);
        $wxUserinfo = json_decode($wxUserinfo,true);
        if(isset($wxUserinfo['errcode']) || empty($wxUserinfo['openid'])){
            if(isset($wxUserinfo['errcode']) && in_array($wxUserinfo['errcode'], $this->refreshTokenCode)){
                $access_token = $this->getAccessToken(true);
            }
            Yii::error('YsWeixin/login GET userinfo wxUserInfoUrl:'.$wxUserInfoUrl.' error:'.print_r($wxUserinfo,true));
            return $this->returnArray([],20,'登录微信失败');
        }
        foreach($wxUserinfo as $key=>$val){
            $weixinData[$key] = $val;
        }

        $userInfo = $this->signup($weixinData);

        if (!empty($userInfo) && Yii::$app->getUser()->login($userInfo,3600 * 720)) {
            Yii::$app->getSession()->setFlash('loginuid', Yii::$app->user->id);
            return $this->returnArray(['url'=>$url],0,'微信注册成功');
        }else{
            Yii::error('YsWeixin/login user error:'.print_r($userInfo->attributes,true));
            return $this->returnArray([],50,'微信注册失败');
        }
    }

    public function appLogin($weixinData){
        $weixinInfo = YwUserWeixin::findOne(['unionid'=>$weixinData['unionid'],'openid'=>$weixinData['openid']]);
        if(!empty($weixinInfo)){
            if (!Yii::$app->user->isGuest && Yii::$app->user->id == $weixinInfo->user_id){
                return $this->returnArray([],0,'登录微信成功');
            }
            if (!empty($weixinInfo->userInfo) && Yii::$app->getUser()->login($weixinInfo->userInfo,3600 * 720)){
                Yii::$app->getSession()->setFlash('loginuid', $weixinInfo->userInfo->id);
                return $this->returnArray([],0,'登录微信成功');
            }
        }
        $weixinData['type'] = 2;
        $weixinData['status'] = 2;
        $weixinData['site_id'] = 16;
        $userInfo = $this->signup($weixinData);

        if (!empty($userInfo) && Yii::$app->getUser()->login($userInfo,3600 * 720)) {
            Yii::$app->getSession()->setFlash('loginuid', Yii::$app->user->id);
            return $this->returnArray([],0,'微信注册成功');
        }else{
            Yii::error('YsWeixin/login user error:'.print_r($userInfo->attributes,true));
            return $this->returnArray([],50,'微信注册失败');
        }
    }



    public function signup($weixinData){
        $userInfo = YwUser::findOne(['weixin_unionid'=>$weixinData['unionid']]);
        $site_id = isset($weixinData['site_id']) ? $weixinData['site_id'] : $this->siteInfo['id']; 
        //用户不存在创建用户
        if(empty($userInfo)){
            $userInfo = new YwUser;
            $ticketInfo = YwTicket::find()->where(['openid'=>$weixinData['openid']])->one();
            if ($ticketInfo){
                $userInfo->invite_value = str_replace("qrscene_","",$ticketInfo->user_id);
                $userInfo->invite_type = 'user';
            }
            $userInfo->nickname = isset($weixinData['nickname']) ? $weixinData['nickname'] : '';
            $userInfo->weixin_unionid = isset($weixinData['unionid']) ? $weixinData['unionid'] : '';
            $userInfo->weixin_openid = isset($weixinData['openid']) ? $weixinData['openid'] : '';
            $userInfo->userimg = isset($weixinData['headimgurl']) ? $weixinData['headimgurl'] : '';
            $userInfo->status = 10;
            $userInfo->site_id = $site_id;
            if($userInfo->save() === false){
                Yii::error('YsWeixin/signup insert user error:'.print_r($userInfo->errors,true));
                return false;
            }
            
            //官方IP被禁止访问
            $userIp = Yii::$app->getRequest()->getUserIP();
            if(!empty($userIp)){
                $userLocation = YsIp::service()->location($userIp);
                if($userLocation['city'] == '深圳' || $userLocation['city'] == '广州'){
                	$userInfo->status = 0;
                	Yii::error('YsWeixin/signup Ip:'.$userIp.' is forbidden');
                	if($userInfo->save() === false){
                		Yii::error('YsWeixin/signup:'.print_r($userInfo->errors,true));
                	}
                	Throw new HttpException(500);
                }
            }
        }

        $weixinInfo = YwUserWeixin::findOne(['unionid'=>$weixinData['unionid'],'openid'=>$weixinData['openid']]);
        //微信用户不存在创建用户
        if(empty($weixinInfo)){
            $weixinData['user_id'] = $userInfo->id;
            if(isset($weixinData['status']) === false && isset($weixinData['subscribe'])){
                $weixinData['status'] = $weixinData['subscribe'];
            }
            $userWeixinInfo = new YwUserWeixin;
            $userWeixinInfo->setAttributes($weixinData);
            $userWeixinInfo->site_id = $site_id;
            if($userWeixinInfo->ip < 0 || !is_numeric($userWeixinInfo->ip)){
                $userWeixinInfo->ip = 0;
            }
            if($userWeixinInfo->save() === false){
                Yii::error('YsWeixin/signup insert userweixin error:'.print_r($userWeixinInfo->errors,true));
            }
        }
        
        return $userInfo;
    }

    public function newSignup($weixinData){
        $weixinInfo = YwUserWeixin::findOne(['unionid'=>$weixinData['unionid']]);
        //微信用户不存在创建用户
        if(empty($weixinInfo)){
            $weixinData['user_id'] = $userInfo->id;
            if(isset($weixinData['status']) === false && isset($weixinData['subscribe'])){
                $weixinData['status'] = $weixinData['subscribe'];
            }
            $userWeixinInfo = new YwUserWeixin;
            $userWeixinInfo->setAttributes($weixinData);
            $userWeixinInfo->site_id = $this->siteInfo['id'];
            if($userWeixinInfo->save() === false){
                Yii::error('YsWeixin/signup insert userweixin error:'.print_r($userWeixinInfo->errors,true));
            }
            //如果是老用户导流
            $userWeixinId = $userWeixinInfo->id;
            $checData = serialize($weixinData);
            $link = Url::to(['site/checkuser','weixinData'=>$checData,'userWeixinId'=>$userWeixinId]);
            header("Location:$link");
        }
        
        $userInfo = YwUser::findOne(['weixin_unionid'=>$weixinData['unionid']]);
        //用户不存在创建用户
        if(empty($userInfo)){
            $userInfo = new YwUser;
            $ticketInfo = YwTicket::find()->where(['openid'=>$weixinData['openid']])->one();
            if ($ticketInfo){
                $userInfo->invite_value = str_replace("qrscene_","",$ticketInfo->user_id);
                $userInfo->invite_type = 'user';
            }
            $userInfo->nickname = isset($weixinData['nickname']) ? $weixinData['nickname'] : '';
            $userInfo->weixin_unionid = isset($weixinData['unionid']) ? $weixinData['unionid'] : '';
            $userInfo->weixin_openid = isset($weixinData['openid']) ? $weixinData['openid'] : '';
            $userInfo->userimg = isset($weixinData['headimgurl']) ? $weixinData['headimgurl'] : '';
            $userInfo->status = 10;
            $userInfo->site_id = $this->siteInfo['id'];
            if($userInfo->save() === false){
                Yii::error('YsWeixin/signup insert user error:'.print_r($userInfo->errors,true));
                return false;
            }
        }

        return $userInfo;
    }
    
    /**
     * 发送红包
     * @param unknown $openid  用户微信openid
     * @param unknown $money  发送红包的金额
     * @param unknown $activityName  红包活动内容
     * @param unknown $wishing  红包祝福语
     * @param unknown $remark  红包备注
     * @return multitype:string
     */
    public function sendRedpack($siteId,$billno,$openid,$money,$activityName,$wishing,$remark){
        $siteInfo = YwSite::findOne($siteId);
        if(empty($siteInfo)){
            Yii::error('YsWeixin/sendRedpack siteinfo null');
            return false;
        }
        $siteParams = json_decode($siteInfo->params,true);
        $nonceStr = $this->createNonceStr(32);//获取随机字符串
        //组装参数
        $parameter = array(
            'nonce_str'      =>   $nonceStr,//随机字符串    
            'mch_billno'     =>   $billno,//商户订单号
            'mch_id'         =>   $siteParams['mchId'],//商户号
            'wxappid'        =>   $siteParams['appId'],//公众号APPID
            'send_name'      =>   $activityName,//商户名称
            're_openid'      =>   $openid,//用户openid
            'total_amount'   =>   $money*100,//红包金额，单位为分
            'total_num'      =>   1,//接受人个数
            'wishing'        =>   $wishing,//祝福语
            'client_ip'      =>   Yii::$app->params['serverIp'],//IP
            'act_name'       =>   $activityName,//活动名称
            'remark'         =>   $remark,//备注
        );

        ksort($parameter);
        $parameterArray = [];
        foreach($parameter as $key=>$val){
            $parameterArray[] = $key.'='.$val;
        }
        $parameter['sign'] = $this->wxMd5Sign(implode('&', $parameterArray),$siteParams['apiKey']);//签名
        $xml1 = $this->wxArrayToXml($parameter);
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
        
        $certPath = Yii::getAlias('@common/cert/'.$siteId.'/');
        $cert = ['cert'=>$certPath.'apiclient_cert.pem', 'key'=>$certPath.'apiclient_key.pem'];
        $xml2 = $this->curl_post_ssl($cert,$url,$xml1);
        if(empty($xml2)){
            Yii::error('YsWeixin/sendRedpack result '.$xml2.' args:'.print_r($parameter,true));
            return ['send_xml'=>$xml1,'result_xml'=>'','result_obj'=>''];
        }
        $result = simplexml_load_string($xml2, 'SimpleXMLElement', LIBXML_NOCDATA);
        if(empty($result)){
            Yii::error('YsWeixin/sendRedpack result xml error args:'.print_r($parameter,true).' XML:'.$xml2);
            return ['send_xml'=>$xml1,'result_xml'=>$xml2,'result_obj'=>''];
        }
        return ['send_xml'=>$xml1,'result_xml'=>$xml2,'result_obj'=>$result];
    }

    /**
     * 红包查询
     * @param unknown $mch_billno
     */
    public function queryRedpack($siteId,$billno){
        $siteInfo = YwSite::findOne($siteId);
        if(empty($siteInfo)){
            Yii::error('YsWeixin/sendRedpack siteinfo null');
            return false;
        }
        $siteParams = json_decode($siteInfo->params,true);
        //获取随机字符串
        $nonce_str = $this->createNonceStr(32);
        //组装参数
        $parameter = array(
            'nonce_str'      =>   $nonce_str,//随机字符串
            'mch_billno'     =>   $billno,//商户订单号
            'mch_id'         =>   $siteParams['mchId'],//商户号
            'appid'          =>   $siteParams['appId'],//公众号APPID
            'bill_type'      =>   'MCHT',//订单类型
        );
        ksort($parameter);
        $parameterArray = [];
        foreach($parameter as $key=>$val){
            $parameterArray[] = $key.'='.$val;
        }
        $parameter['sign'] = $this->wxMd5Sign(implode('&', $parameterArray),$siteParams['apiKey']);//签名
        $xml1 = $this->wxArrayToXml($parameter);
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";
        
        $certPath = Yii::getAlias('@common/cert/'.$siteId.'/');
        $cert = ['cert'=>$certPath.'apiclient_cert.pem', 'key'=>$certPath.'apiclient_key.pem'];
        $xml2 = $this->curl_post_ssl($cert, $url, $xml1);
        if(empty($xml2)){
            Yii::error('YsWeixin/queryRedpack result '.$xml2.' args:'.print_r($parameter,true));
            return ['send_xml'=>$xml1,'result_xml'=>'','result_obj'=>''];
        }
        $result = simplexml_load_string($xml2, 'SimpleXMLElement', LIBXML_NOCDATA);
        if(empty($result)){
            Yii::error('YsWeixin/queryRedpack result xml error args:'.print_r($parameter,true).' XML:'.$xml2);
            return ['send_xml'=>$xml1,'result_xml'=>$xml2,'result_obj'=>''];
        }
        return ['send_xml'=>$xml1,'result_xml'=>$xml2,'result_obj'=>$result];
    }

    //生成签名
    public function wxMd5Sign($content,$apiKey){
        try {
            if (is_null($apiKey)) {
                throw new Exception("财付通签名key不能为空！");
            }
            if (is_null($content)) {
                throw new Exception("财付通签名内容不能为空");
            }
            $signStr = $content . "&key=" . $apiKey;
            return strtoupper(md5($signStr));
        }
        catch (Exception $e)
        {
            die($e->getMessage());
        }
    }
    //将数组解析成xml
    public function wxArrayToXml($parameters = NULL){
        if(!is_array($parameters) || empty($parameters)){
            die("参数不为数组无法解析");
        }
        $xml = "<xml>\n";
        foreach ($parameters as $key=>$val){
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">\n";
        }
        $xml.="</xml>\n";
        return $xml;
    }

    //微信支付，红包
    public function curl_post_ssl($cert, $url, $vars, $second=30,$aHeader=array())
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

        //以下两种方式需选择一种

        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT,$cert['cert']);
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,$cert['key']);

        //第二种方式，两个文件合成一个.pem文件
//         curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');

        if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        }else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }
}
